package com.yantong.controller.aftersale;

import com.yantong.annotation.Log;
import com.yantong.constant.WorkOrderStatus;
import com.yantong.controller.BaseController;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.service.ConfigService;
import com.yantong.pojo.vo.ListWorkOrderVo;
import com.yantong.pojo.WorkComment;
import com.yantong.pojo.WorkConfig;
import com.yantong.pojo.WorkOrder;
import com.yantong.service.WorkClassService;
import com.yantong.service.WorkOrderService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 售后工单控制类
 * @author kanghaixin
 * @date 2018/9/3.16:08
 */
@Controller
@RequestMapping("/sales/order")
public class WorkOrderController extends BaseController {

    private static final String prefix = "workorder/order";

    private static final Logger logger = LoggerFactory.getLogger(WorkOrderController.class);
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private WorkClassService workClassService;

    /**
     * 工单列表
     * @return
     */
    @RequiresPermissions("sales:order:order")
    @GetMapping()
    public String orders(Model model) {
        model.addAttribute("imgPrefix", configService.getImgPrefix());
        model.addAttribute("statusList", WorkOrderStatus.getWorkOrderStausList());
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/orders";
    }


    /**
     * 工单列表数据
     * @param listWorkOrderVo
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("sales:order:order")
    public PageUtils<WorkOrder> listWorkOrders(ListWorkOrderVo listWorkOrderVo, int offset, int limit) {
        listWorkOrderVo.setTeamId(getUserTeamId());
        return workOrderService.listWorkOrders(listWorkOrderVo, offset, limit);
    }
    
    /**
     * 售后工单总计
     * @param listWorkOrderVo
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/sumWorkMoney")
    public ResultVo sumWorkMoney(ListWorkOrderVo listWorkOrderVo) {
    	ResultVo resultVo = new ResultVo();
    	resultVo.put("sumMoney", workOrderService.sumWorkMoney(listWorkOrderVo));
        return resultVo ;
    }


    /**
     * 工单导出
     * @param listWorkOrderVo
     * @param response
     */
    @RequiresPermissions("sales:order:export")
    @GetMapping("/exportWorkOrders")
    public void exportWorkOrders(ListWorkOrderVo listWorkOrderVo, HttpServletResponse response) {
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"工单号", "门店姓名", "门店ID", "门店手机","上级门店", "上级门店ID","工单内容","评估客服","订单区域",
                "售后数量","责任方", "工单类型", "工单原因", "订单编号","商品信息","上架时间段", "供应商","成本价","佣金", "应付价",
                "运送车次", "下单信息","微信退款","余额退款","总退款","申请时间", "操作财务", "操作时间"};
        resultData.add(0, Arrays.asList(head));
        List<WorkOrder> list = workOrderService.listWorkOrder(listWorkOrderVo);
        if (CollectionUtils.isNotEmpty(list)) {
            for (WorkOrder wo: list) {
                if (wo == null) {
                    continue;
                }
                List<Object> row = new ArrayList<>();
                row.add(wo.getWorksn());
                row.add(wo.getRealname());
                row.add(wo.getMid());
                row.add(wo.getMobile());
                row.add(wo.getUpRealname());
                row.add(wo.getUpMid());
                row.add(wo.getContents());
                row.add(wo.getKefuname());
                row.add(wo.getCity());
                row.add(wo.getNums());
                row.add(StringUtils.isEmpty(wo.getResponse())?"供应商":wo.getResponse());
                row.add(wo.getTypename());
                row.add(wo.getCause());
                row.add(wo.getOrdersn());
                row.add("商品编号:"+ wo.getGoodscode()+ "商品名称:"+ wo.getShortTitle()+ "供应商名称:"+ wo.getSupplyName()+ "成本价:"+ wo.getCostprice()+
                        "应付价:"+ wo.getMarketprice() + "数量:"+ wo.getTotal()+ "总价:"+ wo.getPrice());
                row.add(DateUtils.formatFull(wo.getUpStartTime()) + "--"+ DateUtils.formatFull(wo.getUpEndTime()));
                row.add(wo.getSupplyName());
                row.add(wo.getCostprice());
                row.add(wo.getCommissionMoney());
                row.add(wo.getMarketprice());
                row.add(wo.getCarName());
                row.add("送货地址:"+ wo.getSaddress()+ "下单人:" + wo.getNickname()+ "收货人:"+ wo.getSname()+ "手机号:"+ wo.getsMobile());
                row.add(wo.getPaymoney());
                row.add(wo.getCredit2money());
                row.add(wo.getMoney());
                row.add(DateUtils.formatFull(wo.getCreateTime()));
                row.add(wo.getCaiwuname());
                row.add(DateUtils.formatFull(wo.getPaytime()));
                resultData.add(row);
            }
        }
        String fileName = "售后工单" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
        try {
            ExcelHelper.exportExcel(response, fileName, "售后工单", resultData);
        } catch (IOException e) {
            logger.info("export workOrder error:{}", e.getMessage());
        }
    }

    /**
     * 逻辑删除
     * @param workId
     * @return
     */
    @Log(module = "工单管理", operation = "删除工单")
    @RequiresPermissions("sales:order:remove")
    @ResponseBody
    @PostMapping("/remove")
    public ResultVo remove(Long workId) {
        if (workId == null) {
            return ResultVo.error();
        }
        WorkOrder workOrder = new WorkOrder();
        workOrder.setId(workId);
        workOrder.setIsdelete(1);
        workOrder.setKefuname(getNikeName());
        workOrder.setKefuid(getUserId());
        if (workOrderService.update(workOrder)< 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 回复页面
     * @param workId
     * @param model
     * @return
     */
    @RequiresPermissions("sales:order:reply")
    @GetMapping("/reply/{workId}")
    public String reply(@PathVariable Long workId, Model model) {
        model.addAttribute("workComments", workOrderService.getWorkComment(workId));
        model.addAttribute("workOrder", workOrderService.getByKey(workId));
        return prefix + "/reply";
    }

    /**
     * 回复查看页面
     * @param workId
     * @param model
     * @return
     */
    @RequiresPermissions("sales:order:reply")
    @GetMapping("/replyRead/{workId}")
    public String replyRead(@PathVariable Long workId, Model model) {
        model.addAttribute("workComments", workOrderService.getWorkComment(workId));
        model.addAttribute("workOrder", workOrderService.getByKey(workId));
        return prefix + "/replyRead";
    }

    /**
     * 新增回复
     * @param workComment
     * @return
     */
    @Log(module = "工单管理", operation = "新增回复")
    @ResponseBody
    @RequiresPermissions("sales:order:saveReply")
    @PostMapping("/saveReply")
    public ResultVo saveReply(WorkComment workComment) {
        if (workComment == null || workComment.getRemark() == null) {
            return ResultVo.error();
        }
        workComment.setKefuId(getUserId());
        workComment.setKefuName(getNikeName());
        if (workOrderService.saveWorkComment(workComment)< 1){
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 工单关闭页面
     * @param workId
     * @param model
     * @return
     */
    @RequiresPermissions("sales:order:close")
    @GetMapping("/closeWorkOrder/{workId}")
    public String closeWorkOrder(@PathVariable Long workId, Model model) {
        model.addAttribute("workId", workId);
        return prefix + "/closeWork";
    }

    /**
     * 工单关闭操作
     * @param workId
     * @param content
     * @return
     */
    @Log(module = "工单管理", operation = "工单关闭操作")
    @ResponseBody
    @RequiresPermissions("sales:order:close")
    @PostMapping("/closeWork")
    public ResultVo closeWork(Long workId, String content) {
        if (workId == null || StringUtils.isEmpty(content)) {
            return ResultVo.error();
        }
        WorkOrder workOrder = new WorkOrder();
        workOrder.setId(workId);
        workOrder.setKefuname(getNikeName());
        workOrder.setKefuid(getUserId());
        workOrder.setKefuContents(content);
        if (workOrderService.closeWork(workOrder)< 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }


    /**
     * 转财务处理页面
     * @param workId
     * @param model
     * @return
     */
    @RequiresPermissions("sales:order:forward")
    @GetMapping("/forwardCw/{workId}")
    public String forwardCw(@PathVariable Long workId, Model model) {
        model.addAttribute("workOrder", workOrderService.getByKey(workId));
        model.addAttribute("workOrderTypes", workClassService.listAllTypes());
        return prefix + "/forwardCw";
    }

    /**
     * 转财务操作
     * @param workOrder
     * @return
     */
    @Log(module = "工单管理", operation = "转财务操作")
    @ResponseBody
    @RequiresPermissions("sales:order:forward")
    @PostMapping("/forward")
    public ResultVo forward(WorkOrder workOrder) {
        if (workOrder == null || workOrder.getId() == null) {
            return ResultVo.error();
        }
        workOrder.setKefuname(getNikeName());
        workOrder.setKefuid(getUserId());
        if (workOrderService.forwardCw(workOrder)< 1){
            return ResultVo.error();
        }
        return ResultVo.ok();
    }


    /**
     * 财务退款
     * @param workId
     * @return
     */
    @Log(module = "工单管理", operation = "财务退款")
    @ResponseBody
    @PostMapping("/refund")
    @RequiresPermissions("finance:workorder:pay")
    public ResultVo cwRefund(Long workId) {
        if (workId == null) {
            return ResultVo.error();
        }
        if (workOrderService.cwRefund(workId, getUserId(),getNikeName())< 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 财务批量打款
     * @param ids
     * @return
     */
    @Log(module = "工单管理", operation = "财务批量打款")
    @ResponseBody
    @RequiresPermissions("finance:workorder:batchPay")
    @PostMapping("/batchRefund")
    public ResultVo cwBatchRefund(@RequestParam("ids[]") Long[] ids) {
        if (ids == null || ids.length <1) {
            return ResultVo.error();
        }
        for (Long workId: ids) {
            int i = workOrderService.cwRefund(workId, getUserId(),getNikeName());
            if(i==1003&&ids.length==1){
            	return ResultVo.error("该商品未收货无法打款!");
            }
        }
        return ResultVo.ok();
    }



    /**
     * 保存工单时效性
     * @param outTime
     * @return
     */
    @RequiresPermissions("sales:order:saveOutTime")
    @ResponseBody
    @PostMapping("/saveOutTime")
    public ResultVo saveOutTime(Integer outTime) {
        outTime = outTime == null? 48:outTime;
        WorkConfig workConfig = new WorkConfig();
        workConfig.setCentreId(getUserCentreId());
        workConfig.setWorkTime(outTime);

        if (workOrderService.saveWorkOutTimeConfig(workConfig)< 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }
}
